<script setup>
import { storeToRefs } from 'pinia'
import { useCommonTypesStore } from '@/stores/commonTypes.js'
import MIcon from '@/components/MIcon.vue'

const props = defineProps({
  api: {
    type: Function,
    default: null
  },
  modelValue: {
    type: [Array, String, Number, Object],
    default: null
  },
  keyLabel: {
    type: Array,
    default: () => ['label']
  },
  labelAddition: {
    type: String,
    default: ''
  },
  keyValue: {
    type: String,
    default: 'value'
  },
  needCache: {
    type: Boolean,
    default: false
  },
  show: {
    type: Boolean,
    default: false
  },
  name: {
    type: String,
    default: null
  },
  keyRes: {
    type: String,
    default: 'data'
  },
  multiple: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: '请选择'
  },
  height: {
    type: String,
    default: '50%'
  },
})
const emits = defineEmits(['update:modelValue', 'update:show', 'confirm'])
const options = ref([])
const store = useCommonTypesStore()
const { state } = storeToRefs(store)
const loading = ref(false)
const showPicker = computed({
  get() {
    return props.show
  },
  set(val) {
    emits('update:show', val)
  }
})

async function initOption() {
  loading.value = true
  try {
    const res = await props?.api?.()
    if (res?.ret === 0 || res?.code === 0) {
      formatOptions(res?.[props.keyRes] || [])
    }
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}

function isArray(value) {
  return Array.isArray(value)
}

function formatOptions(data, isSave = true) {
  let keyLabel = ''
  let keyValue = ''
  if (props?.formatRes) {
    data = props?.formatRes(data)
  }
  options.value = data.map((item) => {
    if (isArray(props.keyLabel)) {
      for (let i = 0; i < props.keyLabel.length; i++) {
        if (item?.[props.keyLabel[i]]) {
          keyLabel = props.keyLabel[i]
          break
        }
      }
    } else {
      keyLabel = props.keyLabel
    }
    if (isArray(props.keyValue)) {
      for (let i = 0; i < props.keyValue.length; i++) {
        if (item?.[props.keyValue[i]]) {
          keyValue = props.keyValue[i]
          break
        }
      }
    } else {
      keyValue = props.keyValue
    }
    return {
      label:
        props.labelAddition && item?.[props.labelAddition]
          ? `${item?.[keyLabel]}(${item?.[props.labelAddition]})`
          : item?.[keyLabel],
      value: item?.[keyValue]
    }
  })
  if (props.needCache && props.name && isSave) {
    store.updateValue(props.name, options.value)
  }
}

if (!state.value?.[props.name]?.length) {
  initOption()
} else if (!state.value?.[props.name]?.[0]?.value) {
  formatOptions(state.value?.[props.name], false)
} else {
  options.value = JSON.parse(JSON.stringify(state.value?.[props.name]))
}

const selectedList = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:model-value', val)
    emits('confirm', val)
  }
})

const toggleState = (item) => {
  const index = selectedList.value.findIndex(
    (selectedItem) => selectedItem.value === item.value
  )
  if (index !== -1) {
    selectedList.value.splice(index, 1)
  } else {
    // 如果未选中，则添加到已选列表
    if (props.multiple) {
      selectedList.value.push(item)
    } else {
      selectedList.value = [item]
    }
  }
}
const isActive = (item) => {
  return (
    selectedList.value.findIndex(
      (selectedItem) => selectedItem.value === item.value
    ) > -1
  )
}
</script>

<template>
  <van-popup
    v-model="showPicker"
    :style="{ height: height }"
    close-icon="arrow-down"
    closeable
    custom-style="border-top-left-radius: 3px;height:'30%', border-top-right-radius: 3px;"
    position="bottom"
    round
  >
    <div class="h-full box-border overflow-hidden flex flex-col">
      <div
        class="px-12px flex items-center border-b-1px h-50px border-b-solid border-b-[#F2F5FA]"
      >
        <span class="text-16px font-600 leading-16px text-#171A1D">
          {{ title }}
        </span>
      </div>
      <div
        class="w-full box-border flex-1 overflow-x-hidden overflow-y-auto pb-40px"
      >
        <ul class="box-border w-full px-16px box-border">
          <li
            v-for="it in options"
            :key="it.value + '2'"
            :class="isActive(it) ? 'active' : ''"
            class="item h-24px relative py-5px text-14px font-400 leading-24px flex justify-between"
            @click="toggleState(it)"
          >
            <span
              class="flex-1 flex h-full overflow-x-auto whitespace-nowrap"
              >{{ it.label }}</span
            >
            <div class="w-20px h-full flex justify-end items-center">
              <span class="text-20px" v-if="isActive(it)">
                <m-icon name="checked" />
              </span>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </van-popup>
</template>
<style lang="less" scoped>
li.active {
  color: #36b374;
}

li.disabled {
  color: #999999;
}
</style>
